class Blackboard {
  constructor(
    public el = document.querySelector<HTMLCanvasElement>('#canvas')!,
    public app = el.getContext('2d')!,
    private height = el.height,
    private width = el.width,

    private bgColor = '#000',
    private lineColor = '#fff'
  ) {
    this.initCanavs()
    this.handleDraw()
    this.handleClear()
    this.handleColor()
    this.handleScreenshot()
    this.handleErase()
  }

  private initCanavs() {
    this.app.fillStyle = this.bgColor
    this.app.fillRect(0, 0, this.width, this.height)
  }

  private drawLine = (e: MouseEvent) => {
    this.app.lineTo(e.offsetX, e.offsetY)
    this.app.stroke()
  }

  private handleDraw() {
    this.el.addEventListener('mousedown', () => {
      this.app.beginPath()
      this.app.strokeStyle = this.lineColor

      this.el.addEventListener('mousemove', this.drawLine)
      document.addEventListener('mouseup', () => {
        this.el.removeEventListener('mousemove', this.drawLine)
      })
    })
  }

  private handleClear() {
    const clearBtn = document.querySelector<HTMLButtonElement>('.clearBtn')!
    clearBtn.addEventListener('click', () => {
      this.app.fillStyle = this.bgColor
      this.app.fillRect(0, 0, this.width, this.height)
    })
  }

  private handleColor() {
    const controllerEl = document.querySelector('.controller')!
    const colorArr = ['white', 'red', 'blue', 'yellow']
    colorArr.forEach(i => {
      const colorEl = document.createElement('div')
      colorEl.style.backgroundColor = i
      colorEl.classList.add('colorBtn')
      controllerEl.appendChild(colorEl)

      colorEl.addEventListener('click', () => {
        this.handleControllerBlur()
        colorEl.classList.add('active')
        this.lineColor = i
        this.app.lineWidth = 2
      })
    })
  }

  private handleErase() {
    const eraserBtn = document.querySelector('.eraserBtn')!
    eraserBtn.addEventListener('click', () => {
      this.handleControllerBlur()
      eraserBtn.classList.add('active')
      this.lineColor = this.bgColor
      this.app.lineWidth = 20
    })
  }

  private handleScreenshot() {
    const screenshotBtn =
      document.querySelector<HTMLButtonElement>('.screenshotBtn')!

    screenshotBtn.addEventListener('click', () => {
      this.el.toBlob(blob => {
        const url = URL.createObjectURL(blob!)
        const a = document.createElement('a')
        a.href = url
        a.download = 'blackboard.png'
        a.click()
      })
    })
  }

  private handleControllerBlur() {
    const controllerEl = document.querySelector('.controller')!
    const activeBtn = controllerEl.querySelector('.active')
    activeBtn && activeBtn.classList.remove('active')
  }
}

new Blackboard()
